<template>
<div class="search" :style="{borderColor: bc}">
  <input type="text"
   v-model.trim="a" 
            @focus ="inputFocus"
             @blur="inputBlur" 
             @keydown.up="keyUp"
             @keydown.down="keyDown">
  <ul v-show ="showList">
   <li v-for="(item,index) in tempList" :key="index" :class="{active: index == setIndex}">
  {{item}}
   </li>
  </ul>
  <div></div>
  </div>
</template>

<script>
export default {
data(){
    return{
    a:'',
    list:[
        'html',
                'css',
                'javascript',
                'nodejs',
                'vuejs',
                'bootstrap',
                'layui',
                'mongodb',
                'jquery',
                'sass',
                'gulp',
                'jsonp',
                'java',
                'jaaa',
                'jab'
    ],
    showList:false,
    setIndex:-1,
tempList:[],
tempVal:'',
bc:'#999',

    }
},

watch:{
    a(val,oldVal){
        this.showList = val.length>0

        if(this.setIndex == -1){
            this.tempVal = val
            this.tempList = this.list.filter(item=>{
                return item.includes(val)
            })
        }
    },
},

methods:{
  inputFocus(){
            this.bc = '#37f'
        },
        inputBlur(){
            this.bc = '#999'
        },

    keyUp(e){
            if(this.selIndex === -1){
                this.selIndex = this.tempList.length - 1
            }else{
                this.selIndex --
            }

            if(this.selIndex != -1){
                this.kw = this.tempList[this.selIndex]
            }else{
                this.kw = this.tempVal
            }
        },

          keyDown(){
            console.log(this.selIndex);

            if(this.selIndex === (this.tempList.length - 1)){
                this.selIndex = -1
            }else{
                this.selIndex ++ 
            }


             
            if(this.selIndex != -1){
                this.kw = this.tempList[this.selIndex]
            }else{
                this.kw = this.tempVal
            }
        },
}


}
</script>

<style>
.search{
    width: 400px;
    border: 4px solid #999;
    border-radius: 5px;
    position: relative;
}
input{
    width: 98%;
    height: 40px;
    border: 0;
    outline: none;
    font-size: 16px;
    border-bottom: 1px solid #eee;
}
ul{
    list-style: none;
    margin: 0;
    padding: 0;
}
li{
    line-height: 30px;
    text-indent: 20px;
    margin: 5px 0px;
}
li:hover{
    background: rgba(51, 119, 255, .2);
}
.active{
    background: rgba(51, 119, 255, .2);
}
</style>